from flask import Blueprint
from flask_restful import Api
from flask_restful.reqparse import RequestParser
from flask_restful import Resource, marshal_with, Api, marshal
from flask import request, Blueprint, session

from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth
from webapp.dto_mapper import plan_page_fields, room_page_fields
from webapp.schema import PlanSchema, RoomSchema
from webapp.service.room_service import RoomService
from webapp.service.teach_service import PlanService

room_app = Blueprint('room', __name__, url_prefix='/api/room')
room_api = Api(room_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('roomname', location='json', type=str, trim=True, required=True)
parser.add_argument('roomtype', location='json', type=int, trim=True, required=True)

@room_api.resource('', '/')
class RoomApi(Resource):
    @oper_log('查询教室', request)
    @check_auth('room:list', request)
    @marshal_with(room_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        return RoomService.query_all(**params_dict)

    @oper_log('新增教室', request)
    @check_auth('room:add', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = RoomSchema()
        curr_room = schema.load(params, unknown="exclude")
        data = session["user"]
        curr_room.create_by = data["username"]
        RoomService.create(curr_room=curr_room)

    @oper_log('删除教室', request)
    @check_auth('room:del', request)
    def delete(self):
        ids = request.get_json()
        room_set = set()
        for _id in ids:
            room_set.add(RoomService.find_by_id(id=_id))
        RoomService.delete(room_set=room_set)

    @oper_log('修改教室', request)
    @check_auth('room:edit', request)
    def put(self):
        parser_put = parser.copy()
        parser_put.parse_args()
        params = request.get_json()
        schema = RoomSchema()
        curr_room = schema.load(params, unknown="exclude")
        data = session["user"]
        curr_room.update_by = data["username"]
        RoomService.update(curr_room=curr_room)
        return None, 204